import Vue from 'vue'
import VueRouter from 'vue-router'
import Register from "@/views/Register.vue";
import Login from "@/views/Login.vue";
import Click from "@/views/Index.vue";
import {getToken} from "@/utils/auth";
import index from "vuex";
import Record from "@/views/Record.vue";

Vue.use(VueRouter)

const routes = [
  {
    path: '/redirect',
    children: [
      {
        path: '/redirect/:path*',
        component: (resolve) => require(['@/views/features/redirect'], resolve)
      }
    ]
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/index',
    component: Click
  },
  {
    path: '/record',
    component: Record
  }
]

const routers = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes
})

routers.beforeEach((to, from, next) => {

  const whiteList = ['/login', '/register']
  console.log(from.fullPath + " " + to.fullPath)
  if (getToken()) {
    console.log("token还在")
    if (to.path === '/login' || to.path === '/register') {
      next({ path: '/index' })
    }
    next()
  }
  else {
    console.log("token不在")
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
  }
})

export default routers
